//
// Created by dxyinme on 2021/10/8.
//

#include "sort_file.h"
#include <cstdlib>
#include <fstream>

namespace Vsort {
namespace FileSort {


SortFile::SortFile(const std::string &file) {
  filename = file;
  // create workplace
  system(("mkdir -p " + filename + WORK_PLACE).c_str());
}

SortFile::~SortFile() {
#ifdef linux
  system(("rm -rf " + filename + WORK_PLACE).c_str());
#else
  system(("del " + filename + WORK_PLACE).c_str());
#endif
}

void SortFile::SetSerializer(Serializer *serializer) {
  serializer_ = serializer;
}

void SortFile::MapFile() {
  auto* f = std::fopen(filename.c_str(), "r");
  size_t buf_size = (1u << 20u);
  char* buf = new char[buf_size];
  int i = 0;
  while (true) {
    int ret = fread(buf, buf_size, 1, f);
    auto* f2 = std::fopen((filename + WORK_PLACE + "/" + std::to_string(++i)).c_str(), "w");
    if (ret <= buf_size) {
      break;
    }
  }
  delete[] buf;

}

void SortFile::ReduceFile() {

}

void SortFile::MergeFiles(size_t i, size_t j) {

}

void SortFile::SortFileTo(const std::string &target_filename) {

}

void SortFile::SortSingleFile(const std::string &file) {
  std::vector<std::string> readall;

}

}
}
